<!--
 * @Date: 2023-03-06 16:04:15
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-07 18:37:28
 * @FilePath: \A19\frontend\src\components\Test\CreateQuestion.vue
-->
<template>
  <el-button type="primary" @click="questionDialog = true"> 创建题目 </el-button>
  <el-dialog
    v-model="questionDialog"
    title="创建题目"
    width="30%"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    
  <el-form ref="ruleFormRef" :model="questionForm" :label-width="60" :rules="rules">
    <el-form-item label="题目" prop="question">
      <el-input v-model="questionForm.question.question" type="textarea"/>
    </el-form-item>
    <ElFormItem label="类型" prop="type">
        <el-radio-group v-model="questionForm.question.type">
            <el-radio label="选择题" />
            <el-radio label="填空题" />
            <el-radio label="简答题" />
            <el-radio label="判断题" />
        </el-radio-group>
    </ElFormItem>
    <ElFormItem label="选项" prop="selections" v-if="['选择题','判断题'].find(s => s === questionForm.question.type)">
        <div class="input-item" v-for="(selection,index) in questionForm.question.selections" :key="index">
            <ElInput ref="inputs" @blur="inputBlur(index)" style="margin-bottom: 18px;" v-model="questionForm.question.selections[index]" ></ElInput>
            <ElButton text icon="Minus" type="danger" @click="deleteSelection(index)"></ElButton>
        </div>
        <ElButton icon="plus" @click="addSelection()"></ElButton>
    </ElFormItem>
    <ElFormItem label="分数">
        <el-input-number v-model="questionForm.question.score" :min="1" />
    </ElFormItem>
    <ElFormItem label="答案" prop="answer" v-if="questionForm.question.type !== '简答题' && questionForm.question.type !== '填空题' && questionForm.question.type">
        <el-checkbox-group :min="1" v-if="questionForm.question.type === '选择题'" v-model="questionForm.answer.selections">
            <el-checkbox :key="index" v-for="(answer,index) in questionForm.question.selections" :label="answer" name="type" />
        </el-checkbox-group>
        <ElRadioGroup v-if="questionForm.question.type === '判断题'" v-model="questionForm.answer.selection">
            <el-radio :key="answer" v-for="(answer,index) in questionForm.question.selections" :label="answer" />
        </ElRadioGroup>
    </ElFormItem>
    <ElFormItem label="填空数" prop="questionCount" v-if="questionForm.question.type === '填空题'">
        <ElInputNumber :min="1" v-model="questionForm.question.questionCount"></ElInputNumber>
    </ElFormItem>
  </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose(undefined)">Cancel</el-button>
        <el-button type="primary" @click="confirm"> Confirm </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { questions } from '../../shared/types/Question';
import { useClientStore } from '../../pinia/stores/client';
import { FormRules,FormInstance } from 'element-plus';

const props = defineProps<{ courseId: string,questions:Array<questions> }>();
const courseId = props.courseId || "63c0c09ae58ff204b7dcceaa";
const client = useClientStore().client

const questionDialog = ref(false)
const ruleFormRef = ref<FormInstance>()
const questionForm = reactive({
    question:{
        question: '',
        type: '' as "选择题" | "填空题" | "简答题" | "判断题",
        selections: new Array<string>,
        score:0,
        questionCount:0
    },
    answer:{
        selections: [],
        // answers: new Array<Array<string>>(),
        selection:'',
    }
})
const rules = reactive<FormRules>({
    question:[
        {
            message:'请输入问题',validator:(rule,value:string,callback)=>{
                if(!questionForm.question.question){
                    callback(new Error())
                }
                else{
                    callback()
                }
            }
        },
        {
            required:true,
        }
    ],
    type:[
        {
            message:'请选择问题类型',validator:(rule,value:string,callback)=>{
                if(!questionForm.question.type){
                    callback(new Error())
                }
                else{
                    callback()
                }
            }
        },
    ],
    selections:[
        {
            message:'请添加选项',
            validator:(_,_2,callback)=>{
                if(questionForm.question.selections.length === 0) callback(new Error)
                else callback()
            }
        }
    ],
    answer:[
        {
            validator:(_,_2,callback)=>{
                if(questionForm.question.type === '选择题'){
                    if(questionForm.answer.selections.length === 0){
                        callback(new Error('请选择答案'))
                    }
                    else{
                        callback()
                    }
                }
                else if(questionForm.question.type === '判断题'){
                    if(!questionForm.answer.selection){
                        callback(new Error('请选择答案'))
                    }
                    else{
                        callback()
                    }
                }
                else{
                    callback()
                }
            }
        }
    ]
})
const confirm = async ()=>{
    if(ruleFormRef.value){
        try {
            await ruleFormRef.value.validate()
            const ret = await client.callApi('QuestionsSys/CreateQuestion',{
                question:{
                    ...questionForm.question,
                    selections:questionForm.question.selections.length === 0?undefined:questionForm.question.selections
                },
                answer:{
                    selection:questionForm.answer.selection || undefined,
                    selections:questionForm.answer.selections.length === 0?undefined:questionForm.answer.selections
                }
            })
            if(ret.isSucc){
                ElMessage.success('创建成功')
                props.questions.push(ret.res.question)
                questionDialog.value = false
                clearForm()
            }
        } catch (error) {
            console.log(error);
        }
    }
    // questionDialog.value = false
    // clearForm()
}
const handleClose = (done: (() => void) | undefined) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
        questionDialog.value = false
        clearForm()
      if(done) done()
    })
    .catch(() => {
      // catch error
    })
}
const clearForm = ()=>{
    //clearForm
    questionForm.question = {
        question: '',
        type: '' as "选择题" | "填空题" | "简答题" | "判断题",
        selections: new Array<string>,
        score:0,
        questionCount:0
    }
    questionForm.answer = {
        selections: [],
        selection:'',
    }
}
const lastScore = ref(0)

const addSelection = ()=>{
    questionForm.question.selections.push('')
    nextTick(()=>{
        inputs.value[inputs.value.length - 1].focus()
    })
}
const inputBlur = (index:number)=>{
    if(!questionForm.question.selections[index]){
        questionForm.question.selections.splice(index,1)
        return
    }

    let count = 0
    questionForm.question.selections.map(selection =>{
        if(selection === questionForm.question.selections[index]) count ++
        if(count >= 2){
            ElMessage.warning('相同的选项')
            questionForm.question.selections.splice(index,1)
            return false
        }
        else{
            return true
        }
    })

    if(questionForm.question.type === '判断题' && questionForm.question.selections.length > 2){
        questionForm.question.selections.length = 2
    }
}
const deleteSelection = (index:number)=>{
    questionForm.question.selections.splice(index,1)
}
const inputs = ref()
watch(() => questionForm.question.type,newValue =>{
    if(questionForm.question.type === '判断题' && questionForm.question.selections.length > 2){
        questionForm.question.selections.length = 2
    }
})

onMounted(()=>{
    // client.callApi('Get/GetQuestions',{

    // })
})
</script>

<style lang="less" scoped>
.input-item{
    width: 100%;
    display: flex;
}
</style>
